import os
from datetime import datetime


class Logger:
    """日志工具类"""
    
    def __init__(self, log_file: str = None):
        if log_file is None:
            log_dir = "logs"
            os.makedirs(log_dir, exist_ok=True)
            log_file = os.path.join(log_dir, f"download_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log")
        
        self.log_file = log_file
    
    def info(self, message: str):
        """输出信息日志"""
        self._log("INFO", message)
        print(f"\033[1;32m[INFO] {message}\033[0m")
    
    def warning(self, message: str):
        """输出警告日志"""
        self._log("WARNING", message)
        print(f"\033[1;33m[WARNING] {message}\033[0m")
    
    def error(self, message: str):
        """输出错误日志"""
        self._log("ERROR", message)
        print(f"\033[1;31m[ERROR] {message}\033[0m")
    
    def _log(self, level: str, message: str):
        """写入日志文件"""
        try:
            with open(self.log_file, 'a', encoding='utf-8') as f:
                timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                f.write(f"[{timestamp}] [{level}] {message}\n")
        except Exception:
            pass  # 忽略日志写入错误
